package com.zis.platform.service.impl;

import com.zis.base.impl.BaseInterImpl;
import com.zis.core.Constant;
import com.zis.core.ResponseEntity;
import com.zis.platform.dao.UserDao;
import com.zis.platform.model.User;
import com.zis.platform.service.IUserInter;
import com.zis.utils.RandomUtil;
import com.zis.utils.SecurityUtil;
import org.beetl.sql.core.SQLManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Create by wangshen 2017/12/21
 */
@Service
@Transactional("txManager")
public class UserInterImpl extends BaseInterImpl<User> implements IUserInter{

    @Autowired
    private UserDao userDao;

    @Autowired
    private SQLManager sqlManager;

    /**
     * 新增用户
     * @param user
     * @return
     * @throws Exception
     */
    @Override
    public String insert(User user) throws Exception {
        String slat = RandomUtil.getRandomStr(16);//16位密码校验码
        String password = SecurityUtil.AESEncode(slat, Constant.DEFAULT_PASSWORD);//密码加密
        user.setSalt(slat);
        user.setPassword(password);
        user.setCreateDate(new Date());
        int num = sqlManager.insert(user);
        if(num > 0){
            return ResponseEntity.createNormalJsonResponse(Constant.DATA_RESULT_SUCCESS);
        }
        return ResponseEntity.createErrorJsonResponse(Constant.DATA_RESULT_ERROR);
    }

    /**
     * 用户信息更新
     * @param user
     * @return
     * @throws Exception
     */
    @Override
    public String update(User user) throws Exception {
        user.setUpdateDate(new Date());
        int num = sqlManager.updateTemplateById(user);
        if(num > 0){
            return ResponseEntity.createNormalJsonResponse(Constant.DATA_RESULT_SUCCESS);
        }
        return ResponseEntity.createErrorJsonResponse(Constant.DATA_RESULT_ERROR);
    }

    /**
     * 根据主键删除
     * @param id
     * @return
     * @throws Exception
     */
    @Override
    public String delete(String id) throws Exception {
        int num = sqlManager.deleteById(User.class,id);
        if(num > 0){
            return ResponseEntity.createNormalJsonResponse(Constant.DATA_RESULT_SUCCESS);
        }
        return ResponseEntity.createErrorJsonResponse(Constant.DATA_RESULT_ERROR);
    }

    /**
     * 根据主键查询
     * @param id
     * @return
     * @throws Exception
     */
    @Override
    public User selectById(String id) throws Exception {
        return sqlManager.unique(User.class, id);
    }

    /**
     * 条件查询
     * @param user
     * @return
     * @throws Exception
     */
    @Override
    public List<User> findByCondition(User user) throws Exception {
        return sqlManager.template(user);
    }
}
